package com.gzc.just.play.last.war.sceneserver.service;

import com.gzc.just.play.last.war.sceneserver.battle.manager.EnhancedBattleSessionManager;
import com.gzc.just.play.last.war.sceneserver.battle.model.BattleUserInfo;
import com.gzc.just.play.last.war.sceneserver.util.BattleMessageParser;
import com.gzc.just.play.last.war.common.handler.VirtualThreadServerFramework;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 战斗消息路由服务
 * 负责将消息路由到正确的处理组件：BattleSession 或 VirtualThreadServerFramework
 */
@Service
public class BattleMessageRoutingService {
    private static final Logger logger = LoggerFactory.getLogger(BattleMessageRoutingService.class);
    
    @Autowired
    private EnhancedBattleSessionManager enhancedBattleSessionManager;
    
    @Autowired
    private BattleMessageParser battleMessageParser;
    
    @Autowired(required = false)
    private VirtualThreadServerFramework virtualThreadServerFramework;
    
    @Autowired
    private BattleMessageService battleMessageService;
    
    /**
     * 路由来自GateServer的消息
     */
    public boolean routeGSMessage(ChannelHandlerContext ctx, int messageId, byte[] messageData) {
        // 解析消息获取用户ID和战斗ID
        Long userId = battleMessageParser.extractUserIdFromMessage(messageId, messageData, ctx);
        Long battleId = battleMessageParser.extractBattleIdFromMessage(messageId, messageData, userId);
        
        logger.debug("Routing GS message: messageId={}, userId={}, battleId={}", 
                    messageId, userId, battleId);
        
        // 如果是战斗相关消息且有战斗ID，尝试路由到BattleSession
        if (battleMessageParser.isBattleRelatedMessage(messageId) && battleId != null) {
            // 直接将消息提交到对应的BattleSession
            boolean success = enhancedBattleSessionManager.submitBattleMessage(battleId, userId, messageId, messageData);
            if (success) {
                logger.debug("Successfully routed message to battle session: battleId={}, messageId={}", 
                            battleId, messageId);
                return true;
            }
            
            // 提交失败，可能是因为战斗不存在或用户不在战斗中
            logger.warn("Failed to route message to battle session: battleId={}, userId={}, messageId={}", 
                       battleId, userId, messageId);
        }
        
        // 非战斗相关消息或无法路由到BattleSession，通过其他方式处理
        return routeNonBattleMessage(ctx, messageId, messageData, userId);
    }
    
    /**
     * 路由来自CentralServer的消息
     */
    public boolean routeCSMessage(int messageId, byte[] messageData) {
        // 解析消息获取用户ID和战斗ID
        Long userId = battleMessageParser.extractUserIdFromMessage(messageId, messageData, null);
        Long battleId = battleMessageParser.extractBattleIdFromMessage(messageId, messageData, userId);
        
        logger.debug("Routing CS message: messageId={}, userId={}, battleId={}", 
                    messageId, userId, battleId);
        
        // 如果是战斗相关消息且有战斗ID，尝试路由到BattleSession
        if (battleMessageParser.isBattleRelatedMessage(messageId) && battleId != null) {
            // 直接将消息提交到对应的BattleSession
            boolean success = enhancedBattleSessionManager.submitBattleMessage(battleId, userId, messageId, messageData);
            if (success) {
                logger.debug("Successfully routed message to battle session: battleId={}, messageId={}", 
                            battleId, messageId);
                return true;
            }
            
            // 提交失败，可能是因为战斗不存在或用户不在战斗中
            logger.warn("Failed to route message to battle session: battleId={}, userId={}, messageId={}", 
                       battleId, userId, messageId);
        }
        
        // 非战斗相关消息或无法路由到BattleSession，通过其他方式处理
        return routeNonBattleMessage(null, messageId, messageData, userId);
    }
    
    /**
     * 处理创建战斗的特殊消息
     */
    public boolean routeCreateBattleMessage(ChannelHandlerContext ctx, int messageId, byte[] messageData) {
        Long userId = battleMessageParser.extractUserIdFromMessage(messageId, messageData, ctx);
        
        if (userId == null) {
            logger.error("Cannot extract user ID from create battle message");
            return false;
        }
        
        // 通过BattleMessageService处理创建战斗请求
        boolean success = battleMessageService.handleCreateBattle(ctx, userId, messageId, messageData);
        if (!success) {
            logger.error("Failed to handle create battle request for user: {}", userId);
        }
        
        return success;
    }
    
    /**
     * 处理加入战斗的特殊消息
     */
    public boolean routeJoinBattleMessage(ChannelHandlerContext ctx, int messageId, byte[] messageData) {
        Long userId = battleMessageParser.extractUserIdFromMessage(messageId, messageData, ctx);
        Long battleId = battleMessageParser.extractBattleIdFromMessage(messageId, messageData, userId);
        
        if (userId == null) {
            logger.error("Cannot extract user ID from join battle message");
            return false;
        }
        
        // 通过BattleMessageService处理加入战斗请求
        boolean success = battleMessageService.handleJoinBattle(ctx, userId, battleId, messageId, messageData);
        if (!success) {
            logger.error("Failed to handle join battle request for user: {}, battle: {}", userId, battleId);
        }
        
        return success;
    }
    
    /**
     * 路由非战斗消息
     */
    private boolean routeNonBattleMessage(ChannelHandlerContext ctx, int messageId, byte[] messageData, Long userId) {
        // 尝试通过BattleMessageService处理
        boolean handledByBattleService = battleMessageService.handleNonBattleMessage(ctx, messageId, messageData, userId);
        if (handledByBattleService) {
            return true;
        }
        
        // 尝试通过VirtualThreadServerFramework处理
        if (virtualThreadServerFramework != null) {
            try {
                virtualThreadServerFramework.processMessage(messageId, messageData, ctx);
                logger.debug("Routed message to VirtualThreadServerFramework: messageId={}", messageId);
                return true;
            } catch (Exception e) {
                logger.error("Failed to route message to VirtualThreadServerFramework: messageId={}", messageId, e);
            }
        }
        
        // 无法路由该消息
        logger.warn("Unable to route message: messageId={}, userId={}", messageId, userId);
        return false;
    }
    
    /**
     * 处理用户断开连接
     */
    public void handleUserDisconnection(ChannelHandlerContext ctx) {
        // 从Netty上下文中获取用户ID
        io.netty.util.AttributeKey<Long> playerIdKey = io.netty.util.AttributeKey.valueOf("playerId");
        Long userId = ctx.channel().attr(playerIdKey).get();
        
        if (userId != null) {
            // 从所有战斗中移除用户
            enhancedBattleSessionManager.removePlayerFromBattle(userId);
            logger.info("User {} disconnected, removed from all battles", userId);
        }
    }
}